<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>帖子管理 - 健康食谱管理系统</title>
    <link href="https://lib.baomitu.com/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://lib.baomitu.com/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            z-index: 100;
            padding: 48px 0 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
            background-color: #f8f9fa;
            width: 250px;
        }
        .sidebar-sticky {
            position: relative;
            top: 0;
            height: calc(100vh - 48px);
            padding-top: .5rem;
            overflow-x: hidden;
            overflow-y: auto;
        }
        .navbar {
            box-shadow: 0 2px 4px rgba(0,0,0,.1);
        }
        main {
            margin-left: 250px;
            padding: 48px 15px 15px;
        }
        .nav-link {
            color: #333;
            padding: 0.8rem 1rem;
        }
        .nav-link:hover {
            background-color: #e9ecef;
        }
        .nav-link.active {
            background-color: #007bff;
            color: white;
        }
        .nav-link i {
            width: 20px;
            text-align: center;
            margin-right: 10px;
        }
        .post-images {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        .post-images img {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 4px;
            cursor: pointer;
        }
        .search-box {
            margin-bottom: 20px;
        }
        .user-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .user-info img {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            object-fit: cover;
        }
        .post-content {
            max-width: 400px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-dark bg-dark fixed-top">
        <div class="container-fluid">
            <span class="navbar-brand">健康食谱后台管理</span>
            <div class="d-flex">
                <span class="navbar-text me-3" id="adminName"></span>
                <button class="btn btn-outline-light btn-sm" onclick="handleLogout()">退出</button>
            </div>
        </div>
    </nav>

    <!-- 侧边栏 -->
    <nav class="sidebar">
        <div class="sidebar-sticky">
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link" href="index.html">
                        <i class="fas fa-home"></i>仪表盘
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="users.html">
                        <i class="fas fa-users"></i>用户管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="recipes.html">
                        <i class="fas fa-utensils"></i>食谱管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="foods.html">
                        <i class="fas fa-apple-alt"></i>食物管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="posts.html">
                        <i class="fas fa-comments"></i>帖子管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="sports.html">
                        <i class="fas fa-running"></i>运动记录
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="diets.html">
                        <i class="fas fa-hamburger"></i>饮食记录
                    </a>
                </li>
            </ul>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <main>
        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="h2">帖子管理</h1>
            </div>

            <!-- 搜索框 -->
            <div class="search-box">
                <div class="input-group">
                    <input type="text" class="form-control" id="searchInput" placeholder="搜索帖子标题或内容...">
                    <button class="btn btn-outline-secondary" type="button" onclick="searchPosts()">
                        <i class="fas fa-search"></i> 搜索
                    </button>
                </div>
            </div>

            <!-- 帖子列表 -->
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>发布者</th>
                            <th>标题</th>
                            <th>内容</th>
                            <th>图片</th>
                            <th>点赞数</th>
                            <th>评论数</th>
                            <th>发布时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="postList">
                        <!-- 帖子列表将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>

            <!-- 分页控件 -->
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center" id="pagination">
                    <!-- 分页按钮将通过JavaScript动态加载 -->
                </ul>
            </nav>
        </div>
    </main>

    <script src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://lib.baomitu.com/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 1;
        
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            showAdminName();
            loadPosts();
        });

        // 显示管理员名称
        function showAdminName() {
            try {
                const adminUser = JSON.parse(localStorage.getItem('adminUser') || '{}');
                document.getElementById('adminName').textContent = adminUser.nickname || adminUser.username || '';
            } catch (error) {
                console.error('显示管理员名称失败:', error);
            }
        }

        // 处理退出登录
        function handleLogout() {
            localStorage.removeItem('adminToken');
            localStorage.removeItem('adminUser');
            window.location.href = '/admin/login.html';
        }

        // 加载帖子列表
        async function loadPosts(page = 1) {
            try {
                const token = localStorage.getItem('adminToken');
                if (!token) {
                    window.location.href = '/admin/login.html';
                    return;
                }

                const searchQuery = document.getElementById('searchInput').value;
                const response = await fetch(`/api/admin/posts?page=${page}&limit=${pageSize}&search=${searchQuery}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    throw new Error('加载帖子列表失败');
                }

                const result = await response.json();
                if (result.code === 0) {
                    renderPostList(result.data.posts);
                    renderPagination(result.data.total);
                }
            } catch (error) {
                console.error('加载帖子列表失败:', error);
                alert('加载帖子列表失败');
            }
        }

        // 渲染帖子列表
        function renderPostList(posts) {
            const tbody = document.getElementById('postList');
            tbody.innerHTML = posts.map(post => `
                <tr>
                    <td>
                        <div class="user-info">
                            <img src="${post.user?.avatar || '/images/default-avatar.png'}" 
                                 alt="avatar"
                                 onerror="this.src='/images/default-avatar.png'">
                            <span>${post.user?.nickname || post.user?.username || '未知用户'}</span>
                        </div>
                    </td>
                    <td>${post.title || ''}</td>
                    <td>
                        <div class="post-content" title="${post.content || ''}">${post.content || ''}</div>
                    </td>
                    <td>
                        <div class="post-images">
                            ${(post.images || []).map(img => `
                                <img src="${img}" 
                                     onclick="window.open('${img}')"
                                     onerror="this.src='/images/default-post.png'"
                                     alt="post image">
                            `).join('') || '无图片'}
                        </div>
                    </td>
                    <td>${post.likes || 0}</td>
                    <td>${post.comments || 0}</td>
                    <td>${formatTime(post.createdAt)}</td>
                    <td>
                        <button class="btn btn-sm btn-danger" onclick="handleDelete(${post.id})">
                            删除
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 渲染分页
        function renderPagination(total) {
            totalPages = Math.ceil(total / pageSize);
            const pagination = document.getElementById('pagination');
            
            let html = `
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">上一页</a>
                </li>
            `;
            
            for (let i = 1; i <= totalPages; i++) {
                html += `
                    <li class="page-item ${currentPage === i ? 'active' : ''}">
                        <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                    </li>
                `;
            }
            
            html += `
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">下一页</a>
                </li>
            `;
            
            pagination.innerHTML = html;
        }

        // 切换页面
        function changePage(page) {
            if (page < 1 || page > totalPages) return;
            currentPage = page;
            loadPosts(page);
        }

        // 搜索帖子
        function searchPosts() {
            currentPage = 1;
            loadPosts(1);
        }

        // 预览图片
        function previewImage(current, images) {
            wx.previewImage({
                current,
                urls: images
            });
        }

        // 格式化时间
        function formatTime(timestamp) {
            const date = new Date(timestamp);
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
        }

        // 处理删除
        async function handleDelete(id) {
            if (!confirm('确定要删除这个帖子吗？')) {
                return;
            }

            try {
                const token = localStorage.getItem('adminToken');
                if (!token) {
                    throw new Error('请先登录');
                }

                const response = await fetch(`/api/admin/posts/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    throw new Error('删除帖子失败');
                }

                const result = await response.json();
                if (result.code === 0) {
                    alert('删除成功');
                    loadPosts(currentPage);
                } else {
                    throw new Error(result.message || '删除失败');
                }
            } catch (error) {
                console.error('删除帖子失败:', error);
                alert(error.message || '删除失败');
            }
        }
    </script>
</body>
</html> 